package com.ys168.gam.shortestpath.util;

import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

/**
 * 绘制箭头算法
 * 
 * @author Jason Krebs
 * @date 2015年2月5日
 */
public class DrawALHelper {

    private static final double AL_LENGTH = 16;// 箭头长度
    private static final double AL_HALF_WIDTH = 4;// 底边的长度

    /**
     * 绘制带箭头的线
     * 
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @param g2
     */
    public static void drawAL(double startX, double startY, double endX, double endY, Graphics2D g2) {
        double awrad = Math.atan(AL_HALF_WIDTH / AL_LENGTH); // 箭头角度
        double arraowLen = Math.sqrt(AL_HALF_WIDTH * AL_HALF_WIDTH + AL_LENGTH * AL_LENGTH); // 箭头的长度
        double[] rotateVec1 = rotateVec(endX - startX, endY - startY, awrad, arraowLen);
        double[] rotateVec2 = rotateVec(endX - startX, endY - startY, -awrad, arraowLen);
        double x3 = endX - rotateVec1[0]; // (x3,y3)是第一端点
        double y3 = endY - rotateVec1[1];
        double x4 = endX - rotateVec2[0]; // (x4,y4)是第二端点
        double y4 = endY - rotateVec2[1];

        g2.draw(new Line2D.Double(startX, startY, endX, endY));

        GeneralPath triangle = new GeneralPath();
        triangle.moveTo(endX, endY);
        triangle.lineTo(x3, y3);
        triangle.lineTo(x4, y4);
        triangle.closePath();

        g2.fill(triangle);
    }

    /**
     * 绘制带箭头的线
     * 
     * @param start
     * @param end
     * @param g2
     */
    public static void drawAL(Point2D start, Point2D end, Graphics2D g2) {
        drawAL(start.getX(), start.getY(), end.getX(), end.getY(), g2);
    }

    /**
     * 计算旋转角度
     * 
     * @param px
     * @param py
     * @param ang
     *            角度
     * @param isChLen
     * @param newLen
     * @return
     */
    private static double[] rotateVec(double px, double py, double ang, double newLen) {
        double mathstr[] = new double[2];
        // 矢量旋转函数，参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
        double vx = px * Math.cos(ang) - py * Math.sin(ang);
        double vy = px * Math.sin(ang) + py * Math.cos(ang);
        double d = Math.sqrt(vx * vx + vy * vy);
        vx = vx / d * newLen;
        vy = vy / d * newLen;
        mathstr[0] = vx;
        mathstr[1] = vy;

        return mathstr;
    }

}
